public class Solution866 {
    public int primePalindrome(int n) {
        while (true){
            while (!isHuiwen(n)){
                n=next(n);
            }
            if (isPrime(n)){
                return n;
            }else {
                n++;
            }
        }
    }

    private int next(int n) {
        String s=String.valueOf(n);
        StringBuilder stringBuilder1=new StringBuilder(s.substring(0,s.length()/2));
        StringBuilder stringBuilder2=new StringBuilder(stringBuilder1).reverse();
        if (s.length()%2==1){
            stringBuilder1.append(s.charAt(s.length()/2));
        }
        int t=Integer.parseInt(stringBuilder1.append(stringBuilder2).toString());
        if (t>n){
            return t;
        }
        if (s.length()%2==1){
            String r=s.substring(0,s.length()/2+1);
            int p=Integer.parseInt(r);
            p++;
            StringBuilder stringBuilder3=new StringBuilder(String.valueOf(p));
            if (String.valueOf(p).length()==r.length()){
                StringBuilder stringBuilder4=new StringBuilder(stringBuilder3);
                stringBuilder4.deleteCharAt(stringBuilder4.length()-1).reverse();
                return Integer.parseInt(stringBuilder3.append(stringBuilder4).toString());
            }else{
                stringBuilder3.deleteCharAt(stringBuilder3.length()-1);
                StringBuilder stringBuilder4=new StringBuilder(stringBuilder3).reverse();
                return Integer.parseInt(stringBuilder3.append(stringBuilder4).toString());
            }
        }else{
            String r=s.substring(0,s.length()/2);
            int p=Integer.parseInt(r);
            p++;
            StringBuilder stringBuilder3=new StringBuilder(String.valueOf(p));
            StringBuilder stringBuilder4;
            if (String.valueOf(p).length()==r.length()){
                stringBuilder4 = new StringBuilder(stringBuilder3).reverse();
            }else{
                stringBuilder4 = new StringBuilder(stringBuilder3);
                stringBuilder4.deleteCharAt(stringBuilder4.length()-1).reverse();
            }
            return Integer.parseInt(stringBuilder3.append(stringBuilder4).toString());
        }
    }

    private boolean isPrime(int n) {
        if (n==1){
            return false;
        }
        for (int i=2;i*i<=n;i++){
            if (n%i==0){
                return false;
            }
        }
        return true;
    }

    private boolean isHuiwen(int n) {
        String s=String.valueOf(n);
        for (int i=0,j=s.length()-1;i<j;i++,j--){
            if (s.charAt(i)!=s.charAt(j)){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new Solution866().primePalindrome(13));
    }
}
